package com.zhanglijie.base.sync.mardwordDetail;

import org.openjdk.jol.info.ClassLayout;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/6/18 0018 15:56
 * 演示可偏向锁-》偏向锁-》轻量级锁-》无锁状态
 */
public class BiasedToSlowLockToNoLockTest {
    static MyObject myObject = null;

    public static void main(String[] args) throws InterruptedException {
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
        }
        myObject = new MyObject();
        System.out.println(" 可偏向锁 ");
        System.out.println(ClassLayout.parseInstance(myObject).toPrintable());
        /**
         * 抢站偏向锁
         */
        Thread t = new Thread(()->{
            synchronized (myObject) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
        });
        t.start();
        t.join();
        System.out.println("t thread 已持有偏向锁 ");
        System.out.println(ClassLayout.parseInstance(myObject).toPrintable());
        new BiasedToSlowLockToNoLockTest().testLock();
        System.out.println("main 线程加锁后");
        System.out.println(ClassLayout.parseInstance(myObject).toPrintable());


    }
    public void testLock(){
        synchronized (myObject){
            System.out.println("已经加锁");
            System.out.println(ClassLayout.parseInstance(myObject).toPrintable());
            System.out.println("将退出锁");
        }
    }
}
